package com.cqan.box.rest.impl;

import java.io.File;
import java.util.Calendar;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.ws.rs.core.HttpHeaders;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;
import com.cqan.box.entity.AppBox;
import com.cqan.box.entity.Application;
import com.cqan.box.entity.Box;
import com.cqan.box.entity.Platform;
import com.cqan.box.entity.MessageDto;
import com.cqan.box.entity.ResultResp;
import com.cqan.box.entity.UserBox;
import com.cqan.box.rest.MessageRestService;
import com.cqan.box.service.AppBoxService;
import com.cqan.box.service.ApplicationService;
import com.cqan.box.service.BoxService;
import com.cqan.box.service.PlatformService;
import com.cqan.box.service.SendMessageTaskService;
import com.cqan.box.service.UserBoxService;
import com.cqan.common.Constant;
import com.cqan.service.rest.BaseRestService;
import com.cqan.util.TokenCachePool;
import com.cqan.util.http.HttpStatus;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

@Component("boxMessageRestService")
public class MessageRestServiceImpl extends BaseRestService  implements MessageRestService {

	@Resource(name="platformService")
	private PlatformService platformService;
	
	@Resource(name="applicationService")
	private ApplicationService applicationService;
	
	@Resource(name="userBoxService")
	private UserBoxService userBoxService;
	
	@Resource(name="sendMessageTaskService")
	private SendMessageTaskService sendMessageTaskService;
	
	@Resource(name="appBoxService")
	private AppBoxService appBoxService;
	
	@Resource
	private BoxService boxService;
	
	
	
	@Override
	public ResultResp login(String name, String pwd) {
		ResultResp resp = new ResultResp();
		resp.setCommand("platformLogin");
		try {
			Platform box = platformService.findBy("serialNum", name);
			if (box!=null&&box.getState()&&box.getPwd().equals(pwd)) {
				String token = TokenCachePool.getInstance().generate();
				resp.setInfocode(HttpStatus.OK);
				resp.setSid(token);
				resp.setMsg("登陆成功");
				return resp;
			}
			resp.setInfocode(HttpStatus.BAD_REQUEST);
		} catch (Exception e) {
			resp.setInfocode(HttpStatus.INTERNAL_SERVER_ERROR);
			e.printStackTrace();
		}
		logger.debug("box login {} pwd {} token={}", new Object[]{name,pwd,resp.getSid()});
		return resp;
	}

	@Override
	public ResultResp platformSend(String dto) {
		ResultResp resp = new ResultResp();
		resp.setCommand("platformSend");
		try {
			List<Map<String,Object>> messages = Lists.newArrayList();
			MessageDto md = JSONObject.parseObject(dto, MessageDto.class);
			String ip = req.getRemoteAddr();
			
			boolean doit = false;
			Platform platform = platformService.findBy("ip", ip);
			if (md!=null) {
				if (platform!=null||TokenCachePool.getInstance().Verify(md.getSid())) {
					doit = true;
				}
				if (doit) {
					resp.setInfocode(HttpStatus.OK);
					resp.setSid(TokenCachePool.getInstance().generate());
					resp.setMsg("发送成功！");
					List<String> asids = md.getAsids();
					if (asids!=null&&asids.size()>0) {
						for (String asid : asids) {
							if (asid!=null) {
								UserBox userBox = userBoxService.findBy("asid", asid);
								if (userBox!=null) {
									Application app = applicationService.findBy("appid",userBox.getAb());
									 if (app!=null) {
										String certFile = app.getCertFile();
										File file = null;
										if (certFile!=null&&!"".equals(certFile)) {
											file = new File(certFile);
										}
										if (file!=null&&!file.exists()) {
											resp.setInfocode(HttpStatus.INTERNAL_SERVER_ERROR);
											resp.setSid(TokenCachePool.getInstance().generate());
											resp.setMsg("应用程序证书不存在！");
											return resp;
										}//time ，oem ， sub ， chan
										Map<String,Object> message = Maps.newHashMap();
										message.put("message", md.getMessage());
										message.put("keystore",app.getCertFile());
										message.put("password",app.getPassword());
										message.put("production", app.getProduction());
										message.put("devices",userBox.getToken());
										message.put("appid", app.getAppid());
										message.put("sid",md.getSid());
										message.put("type",md.getType());
										message.put("tm",md.getTm());
										message.put("oem",md.getOem());
										message.put("sub",md.getSub());
										message.put("chan",md.getChan());
										messages.add(message);
										//
									}else{
										resp.setInfocode(HttpStatus.INTERNAL_SERVER_ERROR);
										resp.setSid(TokenCachePool.getInstance().generate());
										resp.setMsg("无此应用程序！");
										return resp;
									}
								}
							}
						}
					}
					sendMessageTaskService.send(messages);
				}else{
					resp.setInfocode(HttpStatus.BAD_REQUEST);
					resp.setMsg("sid无效或无绑定IP！");
				}
			}else{
				resp.setInfocode(HttpStatus.BAD_REQUEST);
				resp.setMsg("非法的请求！");
			}
		} catch (Exception e) {
			resp.setInfocode(HttpStatus.INTERNAL_SERVER_ERROR);
			resp.setMsg("服务器异常！");
			e.printStackTrace();
		}
		return resp;
	}

	@Override
	public ResultResp appSetup(String asid,String token, HttpHeaders headers) {
		ResultResp resp = new ResultResp();
		resp.setCommand("appSetup");
		try {
			Map<String, String> header = Constant.getHeader(headers);
			String did = header.get("did");
			String ab = header.get("ab");
			if (token==null||"".equals(token)||did==null||"".equals(did)) {
				resp.setInfocode(HttpStatus.BAD_REQUEST);
				resp.setMsg("请求参数异常！");
				return resp;
			}
			AppBox appbox = null;
			if (asid==null||"".equals(asid)) {
				appbox = appBoxService.getAppBox(ab, did);
				asid = Constant.random();
				if (appbox==null) {
					appbox = new AppBox();
					appbox.setDid(did);
					appbox.setAppid(ab);
					appbox.setCtime(Calendar.getInstance().getTime());
				}
			}else{
				appbox = appBoxService.findBy("asid", asid);
			}
			if (appbox==null) {
				resp.setInfocode(HttpStatus.BAD_REQUEST);
				resp.setMsg("asid 不存在！");
				return resp;
			}
			appbox.setToken(token);
			appbox.setAsid(asid);
			appBoxService.update(appbox);
			resp.setInfocode(HttpStatus.OK);
			resp.setMsg("操作成功！");
			resp.setAsid(asid);
			return resp;
		} catch (Exception e) {
			resp.setInfocode(HttpStatus.INTERNAL_SERVER_ERROR);
			resp.setMsg("服务器异常！");
			e.printStackTrace();
		}
		return resp;
	}


	@Override
	public ResultResp appReg(String asid,String boxid, HttpHeaders headers) {
		ResultResp resp = new ResultResp();
		resp.setCommand("appReg");
		try {
			if (asid==null||boxid==null||headers==null) {
				resp.setInfocode(HttpStatus.BAD_REQUEST);
				resp.setMsg("请求参数异常！");
				return resp;
			}
			AppBox  appbox = appBoxService.findBy("asid", asid);
			if (appbox==null) {
				resp.setInfocode(HttpStatus.BAD_REQUEST);
				resp.setMsg("asid不存在！");
				return resp;
			}
			List<Box> boxs = appbox.getBoxs();
			if (boxs==null) {
				boxs = Lists.newArrayList();
			}
			Box box = boxService.findBy("boxid", boxid);
			if (!boxs.contains(box)) {
				boxs.add(box);
				appBoxService.update(appbox);
			}
			
		} catch (Exception e) {
			resp.setInfocode(HttpStatus.INTERNAL_SERVER_ERROR);
			resp.setMsg("操作失败！");
			e.printStackTrace();
		}
		resp.setInfocode(HttpStatus.OK);
		resp.setMsg("注册成功！");
		return resp;
	}

	@Override
	public ResultResp boxSetup(String boxid,HttpHeaders headers) {
		ResultResp resp = new ResultResp();
		resp.setCommand("boxSetup");
		try {
			Box box = new Box();
			if (boxid==null&&"".equals(boxid)) {
				boxid = Constant.random();
				box.setBoxid(boxid);
				box.setState(true);
				box.setCtime(Calendar.getInstance().getTime());
				Map<String, String> header = Constant.getHeader(headers);
				box.setManufacturer(header.get("flat"));
			}else{
				box = boxService.findBy("boxid", boxid);
				if (box==null) {
					box = new Box();
					box.setBoxid(boxid);
					box.setState(true);
					box.setCtime(Calendar.getInstance().getTime());
					Map<String, String> header = Constant.getHeader(headers);
					box.setManufacturer(header.get("flat"));
				}
			}
			resp.setBoxid(boxid);
			resp.setInfocode(HttpStatus.OK);
			resp.setMsg("操作成功!");
			resp.setSid(TokenCachePool.getInstance().generate());
			boxService.add(box);
		} catch (Exception e) {
			resp.setInfocode(HttpStatus.INTERNAL_SERVER_ERROR);
			resp.setMsg("操作失败!");
			e.printStackTrace();
		}
		return resp;
	}

	@Override
	public ResultResp boxSend(String dto) {
		ResultResp resp = new ResultResp();
		resp.setCommand("boxSend");
		//有效的asids
		List<String> appasids = Lists.newArrayList();
		try {
			List<Map<String,Object>> messages = Lists.newArrayList();
			MessageDto md = JSONObject.parseObject(dto, MessageDto.class);
			if (md!=null&&TokenCachePool.getInstance().Verify(md.getSid())) {
				resp.setInfocode(HttpStatus.OK);
				resp.setSid(TokenCachePool.getInstance().generate());
				resp.setMsg("发送成功！");
				List<String> asids = md.getAsids();
				if (asids!=null&&asids.size()>0) {
					for (String asid : asids) {
						if (asid!=null) {
							String boxid = md.getBoxid();
							if (boxid==null) {
								resp.setInfocode(HttpStatus.BAD_REQUEST);
								resp.setSid(TokenCachePool.getInstance().generate());
								resp.setMsg("请求参数不正确！！");
								return resp;
							}
							AppBox appbox = appBoxService.findBy("asid", asid);
							if (appbox!=null) {
								List<Box> boxs = appbox.getBoxs();
								if (boxs!=null) {
									for (Box box : boxs) {
										if (boxid.equals(box.getBoxid())) {
											Application app = applicationService.findBy("appid",appbox.getAppid());
											 if (app!=null&&asids.contains(appbox.getAsid())) {
												String certFile = app.getCertFile();
												File file = null;
												if (certFile!=null&&!"".equals(certFile)) {
													file = new File(certFile);
												}
												if (file!=null&&!file.exists()) {
													resp.setInfocode(HttpStatus.INTERNAL_SERVER_ERROR);
													resp.setSid(TokenCachePool.getInstance().generate());
													resp.setMsg("应用程序证书不存在！");
													return resp;
												}
												Map<String,Object> message = Maps.newHashMap();
												message.put("message", StringUtils.defaultIfEmpty(md.getMessage(), "无"));
												message.put("keystore",app.getCertFile());
												message.put("password",app.getPassword());
												message.put("production", app.getProduction());
												message.put("devices",appbox.getToken());
												message.put("appid", app.getAppid());
												message.put("sid",md.getSid());
												message.put("boxid",boxid);
												message.put("type",md.getType());
												message.put("acme",md.getAcme());
												message.put("tm",md.getTm());
												message.put("oem",md.getOem());
												message.put("sub",md.getSub());
												message.put("chan",md.getChan());
												messages.add(message);
												appasids.add(asid);
												UserBox ub = new UserBox();
												ub.setAb(appbox.getAppid());
												ub.setAsid(asid);
												ub.setBoxid(boxid);
												ub.setToken(appbox.getToken());
												ub.setCtime(Calendar.getInstance().getTime());
												ub.setDid(appbox.getDid());
												userBoxService.add(ub);
											}else{
												resp.setInfocode(HttpStatus.INTERNAL_SERVER_ERROR);
												resp.setSid(TokenCachePool.getInstance().generate());
												resp.setMsg("无此应用程序！");
												return resp;
											}
										}
									}
								}
							}
						}
					}
				}
				sendMessageTaskService.send(messages);
			}else{
					resp.setInfocode(HttpStatus.BAD_REQUEST);
					resp.setMsg("sid无效！");
				}
		} catch (Exception e) {
			resp.setInfocode(HttpStatus.INTERNAL_SERVER_ERROR);
			resp.setMsg("服务器异常！");
			e.printStackTrace();
		}
		resp.setAsids(appasids);
		return resp;
	}



}
